use serde::{Deserialize, Serialize};
use std::path::Path;
use std::env;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    pub server: ServerSettings,
    pub database: DatabaseSettings,
    pub security: SecuritySettings,
    pub filesystem: FileSystemSettings,
    pub logging: LoggingSettings,
    pub transfer: TransferSettings,
    pub performance: PerformanceSettings,
    pub monitoring: MonitoringSettings,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerSettings {
    pub host: String,
    pub port: u16,
    pub max_connections: u32,
    pub connection_timeout: u64,
    pub data_connection_timeout: u64,
    pub welcome_message: String,
    pub enable_anonymous: bool,
    pub anonymous_home: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseSettings {
    pub path: String,
    pub max_connections: u32,
    pub connection_timeout: u64,
    pub enable_migrations: bool,
    pub backup_enabled: bool,
    pub backup_interval: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecuritySettings {
    pub password_min_length: usize,
    pub max_login_attempts: u32,
    pub session_timeout: u64,
    pub enable_ip_whitelist: bool,
    pub ip_whitelist: Vec<String>,
    pub enable_ip_blacklist: bool,
    pub ip_blacklist: Vec<String>,
    pub enable_ssl: bool,
    pub ssl_cert_path: String,
    pub ssl_key_path: String,
    pub enable_password_policy: bool,
    pub password_policy: PasswordPolicy,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PasswordPolicy {
    pub require_uppercase: bool,
    pub require_lowercase: bool,
    pub require_numbers: bool,
    pub require_special_chars: bool,
    pub max_password_age: u64,
    pub password_history_count: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileSystemSettings {
    pub root_directory: String,
    pub enable_virtual_fs: bool,
    pub max_file_size: u64,
    pub allowed_extensions: Vec<String>,
    pub blocked_extensions: Vec<String>,
    pub enable_quota: bool,
    pub default_quota: u64,
    pub enable_compression: bool,
    pub compression_level: u8,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingSettings {
    pub level: String,
    pub file: String,
    pub max_file_size: u64,
    pub max_files: u32,
    pub format: String,
    pub enable_console: bool,
    pub enable_rotation: bool,
    pub enable_audit_log: bool,
    pub audit_log_file: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransferSettings {
    pub max_transfer_speed: u64,
    pub enable_resume: bool,
    pub chunk_size: usize,
    pub enable_checksum: bool,
    pub checksum_algorithms: Vec<String>,
    pub enable_encryption: bool,
    pub encryption_algorithm: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceSettings {
    pub enable_caching: bool,
    pub cache_size: usize,
    pub cache_ttl: u64,
    pub enable_connection_pooling: bool,
    pub pool_size: u32,
    pub enable_async_io: bool,
    pub io_threads: usize,
    // 性能优化新增字段
    pub buffer_size: usize,
    pub zero_copy_enabled: bool,
    pub batch_size: usize,
    pub prefetch_enabled: bool,
    pub connection_pool_size: usize,
    pub transfer_chunk_size: usize,
    pub enable_performance_monitoring: bool,
    pub metrics_collection_interval: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringSettings {
    pub enable_metrics: bool,
    pub metrics_port: u16,
    pub enable_health_check: bool,
    pub health_check_interval: u64,
    pub enable_performance_monitoring: bool,
    pub performance_log_interval: u64,
}

impl ServerConfig {
    /// 从文件加载配置
    pub fn load<P: AsRef<Path>>(path: P) -> anyhow::Result<Self> {
        let content = std::fs::read_to_string(path)?;
        let mut config: ServerConfig = toml::from_str(&content)?;
        
        // 应用环境变量覆盖
        config.apply_env_overrides()?;
        
        config.validate()?;
        Ok(config)
    }
    
    /// 从环境变量加载配置
    pub fn load_from_env() -> anyhow::Result<Self> {
        let mut config = Self::default();
        config.apply_env_overrides()?;
        config.validate()?;
        Ok(config)
    }
    
    /// 应用环境变量覆盖
    fn apply_env_overrides(&mut self) -> anyhow::Result<()> {
        // 服务器设置
        if let Ok(host) = env::var("FTP_SERVER_HOST") {
            self.server.host = host;
        }
        if let Ok(port) = env::var("FTP_SERVER_PORT") {
            self.server.port = port.parse()?;
        }
        if let Ok(max_conn) = env::var("FTP_MAX_CONNECTIONS") {
            self.server.max_connections = max_conn.parse()?;
        }
        if let Ok(timeout) = env::var("FTP_CONNECTION_TIMEOUT") {
            self.server.connection_timeout = timeout.parse()?;
        }
        if let Ok(welcome) = env::var("FTP_WELCOME_MESSAGE") {
            self.server.welcome_message = welcome;
        }
        if let Ok(anonymous) = env::var("FTP_ENABLE_ANONYMOUS") {
            self.server.enable_anonymous = anonymous.parse()?;
        }
        
        // 数据库设置
        if let Ok(db_path) = env::var("FTP_DATABASE_PATH") {
            self.database.path = db_path;
        }
        if let Ok(db_max_conn) = env::var("FTP_DB_MAX_CONNECTIONS") {
            self.database.max_connections = db_max_conn.parse()?;
        }
        
        // 安全设置
        if let Ok(min_length) = env::var("FTP_PASSWORD_MIN_LENGTH") {
            self.security.password_min_length = min_length.parse()?;
        }
        if let Ok(max_attempts) = env::var("FTP_MAX_LOGIN_ATTEMPTS") {
            self.security.max_login_attempts = max_attempts.parse()?;
        }
        if let Ok(session_timeout) = env::var("FTP_SESSION_TIMEOUT") {
            self.security.session_timeout = session_timeout.parse()?;
        }
        if let Ok(enable_ssl) = env::var("FTP_ENABLE_SSL") {
            self.security.enable_ssl = enable_ssl.parse()?;
        }
        if let Ok(ssl_cert) = env::var("FTP_SSL_CERT_PATH") {
            self.security.ssl_cert_path = ssl_cert;
        }
        if let Ok(ssl_key) = env::var("FTP_SSL_KEY_PATH") {
            self.security.ssl_key_path = ssl_key;
        }
        
        // 文件系统设置
        if let Ok(root_dir) = env::var("FTP_ROOT_DIRECTORY") {
            self.filesystem.root_directory = root_dir;
        }
        if let Ok(max_file_size) = env::var("FTP_MAX_FILE_SIZE") {
            self.filesystem.max_file_size = max_file_size.parse()?;
        }
        if let Ok(enable_quota) = env::var("FTP_ENABLE_QUOTA") {
            self.filesystem.enable_quota = enable_quota.parse()?;
        }
        if let Ok(default_quota) = env::var("FTP_DEFAULT_QUOTA") {
            self.filesystem.default_quota = default_quota.parse()?;
        }
        
        // 日志设置
        if let Ok(log_level) = env::var("FTP_LOG_LEVEL") {
            self.logging.level = log_level;
        }
        if let Ok(log_file) = env::var("FTP_LOG_FILE") {
            self.logging.file = log_file;
        }
        if let Ok(log_format) = env::var("FTP_LOG_FORMAT") {
            self.logging.format = log_format;
        }
        if let Ok(enable_console) = env::var("FTP_LOG_CONSOLE") {
            self.logging.enable_console = enable_console.parse()?;
        }
        
        // 传输设置
        if let Ok(max_speed) = env::var("FTP_MAX_TRANSFER_SPEED") {
            self.transfer.max_transfer_speed = max_speed.parse()?;
        }
        if let Ok(enable_resume) = env::var("FTP_ENABLE_RESUME") {
            self.transfer.enable_resume = enable_resume.parse()?;
        }
        if let Ok(chunk_size) = env::var("FTP_CHUNK_SIZE") {
            self.transfer.chunk_size = chunk_size.parse()?;
        }
        if let Ok(enable_checksum) = env::var("FTP_ENABLE_CHECKSUM") {
            self.transfer.enable_checksum = enable_checksum.parse()?;
        }
        
        // 性能设置
        if let Ok(enable_cache) = env::var("FTP_ENABLE_CACHE") {
            self.performance.enable_caching = enable_cache.parse()?;
        }
        if let Ok(cache_size) = env::var("FTP_CACHE_SIZE") {
            self.performance.cache_size = cache_size.parse()?;
        }
        if let Ok(io_threads) = env::var("FTP_IO_THREADS") {
            self.performance.io_threads = io_threads.parse()?;
        }
        
        // 监控设置
        if let Ok(enable_metrics) = env::var("FTP_ENABLE_METRICS") {
            self.monitoring.enable_metrics = enable_metrics.parse()?;
        }
        if let Ok(metrics_port) = env::var("FTP_METRICS_PORT") {
            self.monitoring.metrics_port = metrics_port.parse()?;
        }
        if let Ok(enable_health) = env::var("FTP_ENABLE_HEALTH_CHECK") {
            self.monitoring.enable_health_check = enable_health.parse()?;
        }
        
        Ok(())
    }
    
    /// 保存配置到文件
    pub fn save<P: AsRef<Path>>(&self, path: P) -> anyhow::Result<()> {
        let content = toml::to_string_pretty(self)?;
        std::fs::write(path, content)?;
        Ok(())
    }
    
    /// 验证配置
    pub fn validate(&self) -> anyhow::Result<()> {
        if self.server.port == 0 {
            return Err(anyhow::anyhow!("Invalid port number"));
        }
        
        if self.security.password_min_length < 6 {
            return Err(anyhow::anyhow!("Password minimum length must be at least 6"));
        }
        
        if self.filesystem.max_file_size == 0 {
            return Err(anyhow::anyhow!("Invalid file size limit"));
        }
        
        if self.security.enable_ssl {
            if self.security.ssl_cert_path.is_empty() || self.security.ssl_key_path.is_empty() {
                return Err(anyhow::anyhow!("SSL certificate and key paths must be specified when SSL is enabled"));
            }
        }
        
        if self.performance.cache_size == 0 && self.performance.enable_caching {
            return Err(anyhow::anyhow!("Cache size must be greater than 0 when caching is enabled"));
        }
        
        if self.monitoring.enable_metrics && self.monitoring.metrics_port == 0 {
            return Err(anyhow::anyhow!("Metrics port must be specified when metrics are enabled"));
        }
        
        Ok(())
    }
    
    /// 获取默认配置
    pub fn default() -> Self {
        Self {
            server: ServerSettings {
                host: "0.0.0.0".to_string(),
                port: 21,
                max_connections: 100,
                connection_timeout: 300,
                data_connection_timeout: 60,
                welcome_message: "Welcome to FTP Server".to_string(),
                enable_anonymous: false,
                anonymous_home: "data/anonymous".to_string(),
            },
            database: DatabaseSettings {
                path: "data/ftp_server.db".to_string(),
                max_connections: 10,
                connection_timeout: 30,
                enable_migrations: true,
                backup_enabled: true,
                backup_interval: 86400, // 24 hours
            },
            security: SecuritySettings {
                password_min_length: 8,
                max_login_attempts: 5,
                session_timeout: 3600,
                enable_ip_whitelist: false,
                ip_whitelist: Vec::new(),
                enable_ip_blacklist: false,
                ip_blacklist: Vec::new(),
                enable_ssl: false,
                ssl_cert_path: String::new(),
                ssl_key_path: String::new(),
                enable_password_policy: true,
                password_policy: PasswordPolicy {
                    require_uppercase: true,
                    require_lowercase: true,
                    require_numbers: true,
                    require_special_chars: false,
                    max_password_age: 7776000, // 90 days
                    password_history_count: 5,
                },
            },
            filesystem: FileSystemSettings {
                root_directory: "data/files".to_string(),
                enable_virtual_fs: true,
                max_file_size: 10737418240, // 10GB
                allowed_extensions: Vec::new(),
                blocked_extensions: vec![".exe".to_string(), ".bat".to_string(), ".cmd".to_string()],
                enable_quota: false,
                default_quota: 1073741824, // 1GB
                enable_compression: false,
                compression_level: 6,
            },
            logging: LoggingSettings {
                level: "info".to_string(),
                file: "logs/ftp_server.log".to_string(),
                max_file_size: 10485760, // 10MB
                max_files: 5,
                format: "json".to_string(),
                enable_console: true,
                enable_rotation: true,
                enable_audit_log: true,
                audit_log_file: "logs/ftp_audit.log".to_string(),
            },
            transfer: TransferSettings {
                max_transfer_speed: 0, // 0 = unlimited
                enable_resume: true,
                chunk_size: 8192,
                enable_checksum: true,
                checksum_algorithms: vec!["md5".to_string(), "sha256".to_string()],
                enable_encryption: false,
                encryption_algorithm: "aes256".to_string(),
            },
            performance: PerformanceSettings {
                enable_caching: true,
                cache_size: 10485760, // 10MB
                cache_ttl: 3600, // 1 hour
                enable_connection_pooling: true,
                pool_size: 100, // 增加连接池大小
                enable_async_io: true,
                io_threads: 8, // 增加IO线程数
                // 性能优化新增字段
                buffer_size: 65536, // 64KB缓冲区
                zero_copy_enabled: true,
                batch_size: 10,
                prefetch_enabled: true,
                connection_pool_size: 1000,
                transfer_chunk_size: 131072, // 128KB传输块
                enable_performance_monitoring: true,
                metrics_collection_interval: 60, // 60秒收集一次指标
            },
            monitoring: MonitoringSettings {
                enable_metrics: true,
                metrics_port: 9090,
                enable_health_check: true,
                health_check_interval: 30,
                enable_performance_monitoring: true,
                performance_log_interval: 300, // 5 minutes
            },
        }
    }
    
    /// 获取配置摘要
    pub fn summary(&self) -> String {
        format!(
            "FTP Server Configuration:\n\
            - Host: {}\n\
            - Port: {}\n\
            - Max Connections: {}\n\
            - SSL Enabled: {}\n\
            - Anonymous Access: {}\n\
            - Root Directory: {}\n\
            - Log Level: {}\n\
            - Metrics Enabled: {}\n\
            - Cache Enabled: {}",
            self.server.host,
            self.server.port,
            self.server.max_connections,
            self.security.enable_ssl,
            self.server.enable_anonymous,
            self.filesystem.root_directory,
            self.logging.level,
            self.monitoring.enable_metrics,
            self.performance.enable_caching
        )
    }
}
